package com.kdfly.zmdfsj;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.gregacucnik.EditableSeekBar;
import com.kdfly.zmdfsj.activity.GmActivity;
import com.kdfly.zmdfsj.adapter.storeAdapter;
import com.kdfly.zmdfsj.data.Game;
import com.kdfly.zmdfsj.entity.Store;
import com.kdfly.zmdfsj.fragment.CommonDialogFragment;
import com.kdfly.zmdfsj.model.Constants;
import com.kdfly.zmdfsj.model.Player;
import com.kdfly.zmdfsj.model.Room;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.lv_store)
    ListView lvStore;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.lv_own)
    ListView lvOwn;
    @BindView(R.id.tv_cash)
    TextView tvCash;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.tv_debt)
    TextView tvDebt;
    @BindView(R.id.btn_debt)
    ImageButton btnDebt;
    @BindView(R.id.btn_bank)
    ImageButton btnBank;
    @BindView(R.id.btn_house)
    ImageButton btnHouse;

    private Random random;
    private int random_num;
    private SimpleAdapter adapter_store;
    private SimpleAdapter adapter_ownstore;
    private List<Map<String, Object>> list_store;
    private List<Map<String, Object>> list_ownstore;

    protected final String SPECIAL_EVENT_GAMEOVER = "==gameover==";
    protected final String SPECIAL_EVENT_QUIT = "==quit==";
    protected final int EVENT_QUEUE_SIZE = 24;
    private final String TAG = "MainActivity";
    protected EventQueue notifications = new EventQueue();
    private View storeHeadView;
    private View ownHeadView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        storeHeadView = getLayoutInflater().inflate(R.layout.listview_top, null);
        ownHeadView = getLayoutInflater().inflate(R.layout.listview_own_top, null);

        EventBus.getDefault().register(this);
        GameEngine.getInstance().init(getApplicationContext());
        ButterKnife.bind(this);
//        btnNext.setText("测试噢。");
        btnNext.setOnClickListener(this);
        btnDebt.setOnClickListener(this);
        btnBank.setOnClickListener(this);
        btnHouse.setOnClickListener(this);

        initGoods();
        initOwnGoods();
        changeGoods();
        changeLocation();

        updateStatus();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_gm) {
            startActivity(new Intent(MainActivity.this, GmActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void changeLocation() {
        GameEngine.getInstance().oneDayPass();

        random = new Random();
        random_num = random.nextInt(9);
//        System.out.println(location[random_num]);

        TextView tvCsAddLink = (TextView) storeHeadView.findViewById(R.id.tv_location);
        tvCsAddLink.setText(Constants.location[random_num]);

        tvDay.setText("第" + GameEngine.getInstance().getDay() + "天");
        changeGoods();
    }

    private void repayDebt() {
        if (GameEngine.getInstance().getPlayer().getDebt() > GameEngine.getInstance().getPlayer().getMoney()) {
            Toast.makeText(getApplicationContext(), R.string.no_enough_debt, Toast.LENGTH_LONG).show();
        } else {
            GameEngine.getInstance().getPlayer().setMoney(GameEngine.getInstance().getPlayer().getMoney() - GameEngine.getInstance().getPlayer().getDebt());
            GameEngine.getInstance().getPlayer().setDebt(0);
        }
        EventBus.getDefault().post(Constants.UPDATE_MONEY);
    }

    private void goToBank() {
        new AlertDialog.Builder(this).setTitle("银行")
                .setMessage("存还是取呢？")
                .setPositiveButton("存", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        showNumberInputDialog(
                                R.drawable.notification_template_icon_bg,
                                R.string.buy,
                                "售出", R.string.ok, R.string.cancel, GameEngine.getInstance().getPlayer().getMoney(),
                                new NumberInputCallback() {
                                    @Override
                                    public void onNumberInputed(int number) {
                                        GameEngine.getInstance().getPlayer().setBank(GameEngine.getInstance().getPlayer().getBank() + number);
                                        GameEngine.getInstance().getPlayer().setMoney(GameEngine.getInstance().getPlayer().getMoney() - number);
                                        EventBus.getDefault().post(Constants.UPDATE_MONEY);
                                    }
                                });
                    }
                })
                .setNegativeButton("取", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        showNumberInputDialog(
                                R.drawable.notification_template_icon_bg,
                                R.string.buy,
                                "售出", R.string.ok, R.string.cancel, GameEngine.getInstance().getPlayer().getBank(),
                                new NumberInputCallback() {
                                    @Override
                                    public void onNumberInputed(int number) {
                                        GameEngine.getInstance().getPlayer().setBank(GameEngine.getInstance().getPlayer().getBank() - number);
                                        GameEngine.getInstance().getPlayer().setMoney(GameEngine.getInstance().getPlayer().getMoney() + number);
                                        EventBus.getDefault().post(Constants.UPDATE_MONEY);
                                    }
                                });
                    }
                })
                .show();
    }

    private storeAdapter storeAdapter;
    private List<Store> mLists;

    private void initGoods() {
        mLists = new ArrayList<>();
        storeAdapter = new storeAdapter(this, mLists);

        lvStore.addHeaderView(storeHeadView, null, false);
        lvStore.setAdapter(storeAdapter);
        lvStore.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final String name = ((TextView) view.findViewById(R.id.goodName)).getText().toString();
                final String pricel = ((TextView) view.findViewById(R.id.goodPrice)).getText().toString();
                final String gid = ((TextView) view.findViewById(R.id.goodid)).getText().toString();

                int getCanBuyAmount = (int) Math.floor(GameEngine.getInstance().getPlayer().getMoney() / Integer.parseInt(pricel));
                int getCanStoreAmount = GameEngine.getInstance().getRoom().getSpace();
                final int maxBuy = getCanBuyAmount > getCanStoreAmount ? getCanStoreAmount : getCanBuyAmount;
//                Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();

//                list_store.remove(position);
//                adapter_store.notifyDataSetChanged();
                showNumberInputDialog(
                        R.drawable.notification_template_icon_bg,
                        R.string.buy,
                        "购买", R.string.ok, R.string.cancel, maxBuy,
                        new NumberInputCallback() {
                            @Override
                            public void onNumberInputed(int number) {
                                if (GameEngine.getInstance().getRoom().getSpace() > 0) {
                                    if (GameEngine.getInstance().getPlayer().getMoney() > Integer.parseInt(pricel)) {
//                                        System.out.println("剩余的空间数：" + GameEngine.getInstance().getRoom().getSpace());

                                        GameEngine.getInstance().buyGood(Integer.parseInt(gid), number);
                                    } else {
                                        Toast.makeText(getApplicationContext(), R.string.no_enough_money, Toast.LENGTH_LONG).show();
                                    }
                                } else {
                                    Toast.makeText(getApplicationContext(), R.string.no_enough_room, Toast.LENGTH_LONG).show();
                                }

//                                ((MainActivity) getActivity()).playSound("buy.wav", 0);
                            }
                        });
            }
        });


//        list_store = new ArrayList<>();
//        View headView = getLayoutInflater().inflate(R.layout.listview_top, null);
//        lvStore.addHeaderView(headView, null, false);
//        adapter_store = new SimpleAdapter(this, list_store, R.layout.listitem_store, new String[]{"name", "price", "gid"}, new int[]{R.id.goodName, R.id.goodPrice, R.id.goodid});
//        lvStore.setAdapter(adapter_store);
//
//
//        lvStore.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//                final String name = ((TextView) view.findViewById(R.id.goodName)).getText().toString();
//                final String pricel = ((TextView) view.findViewById(R.id.goodPrice)).getText().toString();
//                final String gid = ((TextView) view.findViewById(R.id.goodid)).getText().toString();
//
//                int getCanBuyAmount = (int) Math.floor(GameEngine.getInstance().getPlayer().getMoney() / Integer.parseInt(pricel));
//                int getCanStoreAmount = GameEngine.getInstance().getRoom().getSpace();
//                final int maxBuy = getCanBuyAmount > getCanStoreAmount ? getCanStoreAmount : getCanBuyAmount;
////                Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
//
////                list_store.remove(position);
////                adapter_store.notifyDataSetChanged();
//                showNumberInputDialog(
//                        R.drawable.notification_template_icon_bg,
//                        R.string.buy,
//                        "购买", R.string.ok, R.string.cancel, maxBuy,
//                        new NumberInputCallback() {
//                            @Override
//                            public void onNumberInputed(int number) {
//                                if (GameEngine.getInstance().getRoom().getSpace() > 0) {
//                                    if (GameEngine.getInstance().getPlayer().getMoney() > Integer.parseInt(pricel)) {
////                                        System.out.println("剩余的空间数：" + GameEngine.getInstance().getRoom().getSpace());
//
//                                        GameEngine.getInstance().buyGood(Integer.parseInt(gid), number);
//                                    } else {
//                                        Toast.makeText(getApplicationContext(), R.string.no_enough_money, Toast.LENGTH_LONG).show();
//                                    }
//                                } else {
//                                    Toast.makeText(getApplicationContext(), R.string.no_enough_room, Toast.LENGTH_LONG).show();
//                                }
//
////                                ((MainActivity) getActivity()).playSound("buy.wav", 0);
//                            }
//                        });
//            }
//        });
    }

    private void changeGoods() {
        mLists.clear();

        int[] price = GameEngine.getInstance().getPrice();
//        mLists = new ArrayList<>();
        for (int i = 0; i < price.length; i++) {
            Store bean = new Store();
            bean.setName(Constants.goods[i]);
            bean.setPrice(price[i]);
            bean.setId(i);
            if (price[i] != 0) {
                mLists.add(bean);
            }
//            mLists.add(bean);
        }
        storeAdapter.notifyDataSetChanged();
    }

    private void initOwnGoods() {
        list_ownstore = new ArrayList<>();

        lvOwn.addHeaderView(ownHeadView, null, false);
        adapter_ownstore = new SimpleAdapter(this, list_ownstore, R.layout.listitem_ownstore, new String[]{"name", "price", "count", "gid"}, new int[]{R.id.goodName, R.id.goodPrice, R.id.goodCount, R.id.goodid});
        lvOwn.setAdapter(adapter_ownstore);


        lvOwn.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String gid = ((TextView) view.findViewById(R.id.goodid)).getText().toString();

                final Room room = GameEngine.getInstance().getRoom();
                final int[] count = room.getGoodsCount();
                final int maxSell = count[Integer.parseInt(gid)];
                final int[] cost = room.getGoodsCost();

                final Player player = GameEngine.getInstance().getPlayer();

                if (GameEngine.getInstance().checkCanSell(Integer.parseInt(gid))) {
                    showNumberInputDialog(
                            R.drawable.notification_template_icon_bg,
                            R.string.buy,
                            "售出", R.string.ok, R.string.cancel, maxSell,
                            new NumberInputCallback() {
                                @Override
                                public void onNumberInputed(int number) {
                                    GameEngine.getInstance().sellGood(Integer.parseInt(gid), number);
                                }
                            });
                } else {
                    Toast.makeText(getApplicationContext(), R.string.cannot_buy, Toast.LENGTH_LONG).show();
                }


            }
        });
    }

//    private void changeGoods() {
//        list_store.clear();
//        int[] price = GameEngine.getInstance().getPrice();
//
//        for (int i = 0; i < price.length; i++) {
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("name", Constants.goods[i]);
//            map.put("price", price[i]);
//            map.put("gid", i);
////            System.out.println(price[i]);
//            if (price[i] != 0) {
//                list_store.add(map);
////                if (price[i] < Constants.goodsPriceBase[i] + Constants.goodsPriceRand[i]/2){
////                    lvStore.
////                }
//            }
//        }
//        adapter_store.notifyDataSetChanged();
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                changeLocation();
                break;
            case R.id.btn_debt:
                repayDebt();
                break;
            case R.id.btn_bank:
                goToBank();
                break;
            case R.id.btn_house:
                addHouse();
                break;
        }
    }

    private void addHouse() {
        new AlertDialog.Builder(this).setTitle("出租屋")
                .setMessage("增加出租屋空间？")
                .setPositiveButton("买", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if (GameEngine.getInstance().getPlayer().getMoney() > 20000){
                            GameEngine.getInstance().getPlayer().setMoney(GameEngine.getInstance().getPlayer().getMoney() - 20000);
                            GameEngine.getInstance().getRoom().addRoom();
                        }
                        updateStatus();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
//                        showNumberInputDialog(
//                                R.drawable.notification_template_icon_bg,
//                                R.string.buy,
//                                "售出", R.string.ok, R.string.cancel, GameEngine.getInstance().getPlayer().getBank(),
//                                new NumberInputCallback() {
//                                    @Override
//                                    public void onNumberInputed(int number) {
//                                        GameEngine.getInstance().getPlayer().setBank(GameEngine.getInstance().getPlayer().getBank() - number);
//                                        GameEngine.getInstance().getPlayer().setMoney(GameEngine.getInstance().getPlayer().getMoney() + number);
//                                        EventBus.getDefault().post(Constants.UPDATE_MONEY);
//                                    }
//                                });
                    }
                })
                .show();
    }

    public interface NumberInputCallback {
        public void onNumberInputed(int number);
    }

    protected void showNumberInputDialog(int iconId, int titleId, String message, int okId, int cancelId, int initNumber, final NumberInputCallback callback) {
//        final EditText input = new EditText(this);

        View view = View.inflate(getApplicationContext(), R.layout.dialog_buy_or_sell, null);

        final TextView tvYouCanBuy = (TextView) view.findViewById(R.id.tv_you_can_buy);
        final EditableSeekBar sbBuyInput = (EditableSeekBar) view.findViewById(R.id.sb_buy_input);

        sbBuyInput.setValue(initNumber);
        sbBuyInput.setMaxValue(initNumber);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(iconId)
                .setTitle(titleId)
                .setMessage(message)
                .setView(view)
                .setPositiveButton(okId,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (null != callback) {
                                    try {
                                        int number = sbBuyInput.getValue();
                                        callback.onNumberInputed(number);
                                    } catch (NumberFormatException ex) {
//                                        EventBus.getDefault().post("error input, not processed here");
                                    }
                                }
                            }
                        })
                .setNegativeButton(cancelId,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        });
        final AlertDialog alert = builder.create();

        alert.show();
    }

    public void onEventMainThread(String event) {
        notifications.add(event);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
//        ButterKnife.unbind(this);
        super.onDestroy();
    }

    //GameEngine use integer to send commands, like update interface and game over
    //MainActivity need to process it if possible
    //while some commands need to be processed after notification dialog(like change tab or restart)
    //so need to be converted with special_event string, and insert into notification queue with EventBus
    public void onEventMainThread(Integer event) {
        switch (event) {
            case Constants.UPDATE_MONEY:
                updateStatus();
                break;
//            case Constants.UPDATE_DAY:
//                updateDay();
//                autoChangeTab();
//                break;
//            case Constants.UPDATE_DEAL:
//                autoChangeTab();
//                break;
//            case Constants.UPDATE_MARKET:
//                break;
            case Constants.UPDATE_ROOM:
                updateStatus();
                break;
//            case Constants.UPDATE_MONEY:
//            case Constants.UPDATE_FAME:
//            case Constants.UPDATE_HEALTH:
//                updateStatus();
//                break;
            case Constants.UPDATE_GAME_OVER:
                //game over may be triggered by health event or time
                //that means maybe some event dialog is in the front
                //so need to use SPECIAL_EVENT_GAMEOVER to trigger some action after event dialog
                EventBus.getDefault().post(SPECIAL_EVENT_GAMEOVER);
//            case Constants.UPDATE_SETTINGS:
//                updateSettings();
//                break;


            case Constants.GOTO_DAY_30:
                GameEngine.getInstance().goToDay(30);
                tvDay.setText("第" + GameEngine.getInstance().getDay() + "天");
        }
    }

    protected void updateStatus() {
        Player player = GameEngine.getInstance().getPlayer();

        list_ownstore.clear();
        Room room = GameEngine.getInstance().getRoom();
        int[] count = room.getGoodsCount();
        int[] cost = room.getGoodsCost();
        for (int i = 0; i < count.length; i++) {
            if (0 != count[i]) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", Constants.goods[i]);
                map.put("price", cost[i] / count[i]);
                map.put("count", count[i]);
                map.put("gid", i);
                list_ownstore.add(map);
            }
        }
        adapter_ownstore.notifyDataSetChanged();


        tvCash.setText("现金：" + player.getMoney());
        tvDebt.setText("贷款：" + player.getDebt());
//        tvRoom.setText("剩余格子：" + GameEngine.getInstance().getRoom().getSpace() + "/100");
        TextView tvCsAddLink = (TextView) ownHeadView.findViewById(R.id.tv_room);
        tvCsAddLink.setText("出租屋(" + GameEngine.getInstance().getRoom().getSpace() + "/" + GameEngine.getInstance().getRoom().getSpace() + ")");
    }

    protected class EventQueue extends ArrayBlockingQueue<String> implements DialogInterface.OnDismissListener {

        private static final long serialVersionUID = 1L;
        protected ReentrantLock mutex = new ReentrantLock();

        public EventQueue() {
            super(EVENT_QUEUE_SIZE);
        }

        @Override
        public boolean add(String e) {
            Log.d(TAG, "===add:" + e);
            boolean ret;
            mutex.lock();
            if (null == peek()) {
                ret = super.add(e);
                processEvent();
            } else
                ret = super.add(e);
            mutex.unlock();
            return ret;
        }

        protected void processEvent() {
            String notify = notifications.peek();
            Log.d(TAG, "notify=" + notify);

            if (null == notify) {    //no events
                return;
            }

            if (SPECIAL_EVENT_QUIT.equals(notify)) {    //quit
                poll();
                MainActivity.this.finish();
                return;
            }
            if (SPECIAL_EVENT_GAMEOVER.equals(notify)) {    //game over restart
                poll();
                alertRanking();
                return;
            }

            String soundwav = null;
            if (notify.startsWith("[")) {//have sound
                int headpos = notify.indexOf(']');
                soundwav = notify.substring(1, headpos);
                notify = notify.substring(headpos + 1);
            }

            CommonDialogFragment.showEventDialog(getString(R.string.notify_title), notify, this, MainActivity.this);
        }

        protected void alertRanking() {
//            final Man man = GameEngine.getInstance().getMan();
//            final int money = man.getCash()+man.getDeposit()-man.getDebt();
//            final int pos = prefman.getPosition(money);
//            if (pos >= 0) {
//                CommonDialogFragment.showTextInputDialog(getString(R.string.dialog_congratulations),
//                        String.format(getString(R.string.title_alert), money, (pos+1), getString(Constants.TITLES[Constants.getRandom(5)])),
//                        prefman.getLastPlayerName(),
//                        new CommonDialogFragment.TextInputCallback() {
//                            @Override
//                            public void onTextInputed(String text) {
//                                if (null == text)
//                                    text = PreferenceManager.DEFAULT_LAST_PLAYER_NAME;
//                                else {
//                                    if ("".equals(text.trim()))
//                                        text = PreferenceManager.DEFAULT_LAST_PLAYER_NAME;
//                                    prefman.setLastPlayerName(text);
//                                }
//                                prefman.addRanking(text, man.getHealth(), man.getFame(), money);
//                            }
//                        },
//                        new DialogInterface.OnDismissListener() {
//                            @Override
//                            public void onDismiss(DialogInterface dialog) {
//                                MainActivity.this.showRankingDialog(pos, new DialogInterface.OnDismissListener() {
//
//                                    @Override
//                                    public void onDismiss(DialogInterface dialog) {
//                                        confirmGameOverRestart();
//                                    }
//                                });
//                            }
//                        },
//                        MainActivity.this);
//            }
//            else {
//                CommonDialogFragment.showEventDialog(getString(R.string.dialog_sorry),
//                        String.format(getString(R.string.title_alert_failed), money),
//                        new DialogInterface.OnDismissListener() {
//                            @Override
//                            public void onDismiss(DialogInterface dialog) {
//                                MainActivity.this.showRankingDialog(pos, new DialogInterface.OnDismissListener() {
//                                    @Override
//                                    public void onDismiss(DialogInterface dialog) {
//                                        confirmGameOverRestart();
//                                    }
//                                });
//                            }
//                        }, MainActivity.this);
//            }
            CommonDialogFragment.showEventDialog(getString(R.string.notify_title),
                    getString(R.string.game_over),
                    new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
//                            System.out.println("##########################zmd#############");
                            confirmGameOverRestart();
                        }
                    }, MainActivity.this);

        }

        protected void confirmGameOverRestart() {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setIcon(R.drawable.dialog_warning)
                    .setTitle(R.string.dialog_restart)
                    .setCancelable(false)
                    .setPositiveButton(R.string.dialog_restart, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
//                            startNewGame();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //quit after the game, should be immediately
                            MainActivity.this.finish();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            mutex.lock();
            Log.d(TAG, "===poll");
            poll();
            processEvent();
            mutex.unlock();
        }

    }

}
